/**
 * 
 */
package jvs.vfs.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author qiangli
 *
 */
public class CounterInputStream extends InputStream {
	private int max;
	
	private int counter;
	
	private InputStream in;
	
	public CounterInputStream(InputStream in, int max) {
		this.in = in;
		this.max = max;
		this.counter = 0;
	}

	public int getCounter() {
		return counter;
	}

	@Override
	public int read() throws IOException {
		if (counter >= max) {
			return -1;
		}
		int c = in.read();
		if (c != -1) {
			counter++;
		}
		return c;
	}

	@Override
	public int available() throws IOException {
		if (counter >= max) {
			return 0;
		}
		return in.available();
	}

	@Override
	public void close() throws IOException {
		in.close();
	}

	@Override
	public boolean markSupported() {
		return in.markSupported();
	}

	@Override
	public void mark(int readlimit) {
		in.mark(readlimit);
	}
	
	@Override
	public void reset() throws IOException {
		in.reset();
	}

	@Override
	public long skip(long n) throws IOException {
		return in.skip(n);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		len = Math.min(len, (max - counter));
		if (len <= 0) {
			return -1;
		}
		int c = in.read(b, off, len);
		if (c != -1) {
			counter += c;
		}
		return c;
	}

	@Override
	public int read(byte[] b) throws IOException {
		return read(b, 0, b.length);
	}
}
